﻿using System;

namespace ViewModelMapper.Extensions
{
    using System.Linq.Expressions;
    using System.Reflection;

    public static class ExpressionExtensions
    {
        public static PropertyInfo GetPropertyInfo<T, U>(this Expression<Func<T, U>> selector)
        {
            return GetBody(selector).GetMemberExpression().Member as PropertyInfo;
        }

        private static MemberExpression GetMemberExpression(this Expression selector)
        {
            switch (selector.NodeType)
            {
                case ExpressionType.MemberAccess:
                    return selector as MemberExpression;

                case ExpressionType.Convert:
                    return ((UnaryExpression)selector).Operand as MemberExpression;

            }

            throw new InvalidOperationException();
        }

        private static Expression GetBody(Expression selector)
        {
            if (selector.NodeType == ExpressionType.Lambda)
            {
                selector = ((LambdaExpression)selector).Body;
            }

            return selector;
        }
    }
}
